package cn.disicn.util;

import java.io.UnsupportedEncodingException;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author Luyao
 * @date 2017年12月12日 上午10:40:07
 * @desc 邮件发送
 */
public class EmailUtil {

	/**
	 * 
	 * @desc 发送附件
	 * @param sendAddress
	 */
	public static void attachmentAddress(String attachment, String sendAddress) {
		String subject = "申请通过-外咖APP任务分发平台";
		String content = "您在外咖APP申请的任务审核通过，附件如下 ：<br/>" + attachment;
		sendEmail(subject, content, sendAddress);
	}

	/**
	 * 
	 * @desc 找回密码
	 * @param sendAddress
	 * @return
	 */
	public static Integer retrievePassword(String sendAddress) {
		Integer code = getRandomCode();
		String subject = "找回密码-外咖APP任务分发平台";
		String content = "您正在找回密码，验证码为：" + code;
		sendEmail(subject, content, sendAddress);
		return code;
	}

	/**
	 * 
	 * @desc 绑定账号
	 * @param sendAddress
	 * @return
	 */
	public static Integer bindAccount(String sendAddress) {
		Integer code = getRandomCode();
		String subject = "绑定邮箱-外咖APP任务分发平台";
		String content = "您正在绑定外咖APP任务分发平台账号，验证码为：" + code;
		sendEmail(subject, content, sendAddress);
		return code;
	}

	private static void sendEmail(String subject, String content,
			String sendAddress) {
		Properties prop = new Properties();
		// 设置邮件服务器主机名
		prop.setProperty("mail.host", "smtp.ym.163.com");
		// 发送服务器需要身份验证
		prop.setProperty("mail.smtp.auth", "true");
		// 发送邮件协议名称
		prop.setProperty("mail.transport.protocol", "smtp");
		// 创建session
		Session session = Session.getInstance(prop);
		// 通过session得到transport对象
		try {
			Transport ts = session.getTransport();
			// 连接邮件服务器：邮箱类型，帐号，授权码代替密码（更安全）
			ts.connect("smtp.ym.163.com", "service@disicn.cn", "disi888888");// 后面的字符是授权码或密码
			// 创建邮件对象
			MimeMessage message = new MimeMessage(session);
			// 指明邮件的发件人
			message.setFrom(new InternetAddress("service@disicn.cn", "帝斯科技"));
			// 指明邮件的收件人
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(
					sendAddress));
			// 邮件的标题
			message.setSubject(subject);
			// 邮件的文本内容
			message.setContent(
					"【深圳市帝斯科技有限公司】" + content + "<br/>如非本人操作，请忽略此邮件",
					"text/html;charset=UTF-8");
			// 发送邮件
			ts.sendMessage(message, message.getAllRecipients());
			ts.close();
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static Integer getRandomCode() {
		return (int) ((Math.random() * 9 + 1) * 100000);
	}

}
